var Http = require('./Http');
var HOST = 'http://10.140.41.108:5000/';
var HOST = 'http://10.140.92.135:5000/';

//var HOST = 'http://10.140.42.10:5000/';

function Request(url, data, method) {
    this._className = 'Request';
    this._url = url;
    this._data = data;
    this._method = method;
}

Request.prototype.exec = function (url, data, method){
    var _url = url || this._url,
        _data = data || this._data,
        _method = method || this._method||'GET';

    if(_url.indexOf('http://') === -1){
        _url = HOST + _url;
    }

    return Http[_method.toLowerCase()](_url, _data);
}

Request.prototype.refresh = function (){
    this.request();
}

function DataSource(data, argv) {
	this.reset(data, argv);
}

DataSource.prototype.exec = function (){
	var _data = this._data;
	if(!_data){ return; }
	if(_data._className=="Request"){
		_data.exec().then(function (data){
			this._argv.onSuccess && this._argv.onSuccess(data);
		}.bind(this), function (data){
            Popup.message({
                content: 'Load Error Status: ' + data.status,
                type: 'danger'
            });
			this._argv.onError && this._argv.onError(data);
		}.bind(this));
	} else {
		this._argv.onSuccess && this._argv.onSuccess(_data);
	}
}

DataSource.prototype.reset = function (data, argv){
    this._data = data;
	this._argv = argv || this._argv || {};
    if(this._argv.autoLoad){
        this.exec();
    }
}

DataSource.prototype.refresh = function (){
	this.exec();
}

module.exports = {
    init: function (url, data, method){
        return new Request(url, data, method);
    },
    post: function (url, data){
        return new Request(url, data, "POST");
    },
    get: function (url, data){
        return new Request(url, data, "GET");
    },
    setHost: function (value){
        HOST = value;
    },
    dataSource: function (data, argv) {
        return new DataSource(data, argv);
    }
}
